﻿//
// WindowsUtitlies.cs
//
// Authors:
//    Claus Jørgensen <10229@iha.dk>
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Media;

namespace RSD.View
{
    public static class WindowsUtilities
    {
        public static TAncestor FindVisualAncestor<TAncestor>(this DependencyObject obj)
                where TAncestor : DependencyObject
        {
            var current = obj;

            do
            {
                if (current is TAncestor)
                {
                    return (TAncestor)current;
                }

                current = VisualTreeHelper.GetParent(current);
            }
            while (current != null);

            return null;
        }

        public static TAncestor FindLogicalAncestor<TAncestor>(this DependencyObject obj)
            where TAncestor : DependencyObject
        {
            var current = obj;

            do
            {
                if (current is TAncestor)
                {
                    return (TAncestor)current;
                }

                current = LogicalTreeHelper.GetParent(current);
            }
            while (current != null);

            return null;
        }

        public static IEnumerable<TAncestor> FindVisualDescendants<TAncestor>(this DependencyObject obj)
            where TAncestor : DependencyObject
        {
            var childrenCount = VisualTreeHelper.GetChildrenCount(obj);

            for (int i = 0; i < childrenCount; i++)
            {
                var child = VisualTreeHelper.GetChild(obj, i);

                if (child is TAncestor)
                {
                    yield return (TAncestor)child;
                }

                foreach (var subChild in FindVisualDescendants<TAncestor>(child))
                {
                    yield return subChild;
                }
            }
        }

        public static IEnumerable<TAncestor> FindLogicalDescendants<TAncestor>(this DependencyObject obj)
            where TAncestor : DependencyObject
        {
            foreach (var child in LogicalTreeHelper.GetChildren(obj).OfType<DependencyObject>())
            {
                if (child is TAncestor)
                {
                    yield return (TAncestor)child;
                }

                foreach (var subChild in FindVisualDescendants<TAncestor>(child))
                {
                    yield return subChild;
                }
            }
        }
    }
}
